package com.meisiabc.app.web.controller;

import com.google.common.io.ByteStreams;
import com.google.zxing.EncodeHintType;
import com.meisiabc.app.service.RecommenderService;
import com.meisiabc.app.web.auth.AssertAuth;
import com.meisiabc.app.web.auth.SecurityContextHolder;
import com.meisiabc.support.Result;
import com.meisiabc.support.qrcode.QRCode;
import com.meisiabc.support.qrcode.image.ImageType;
import com.meisiabc.utils.MobileUtils;
import com.meisiabc.utils.Verify;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/recommender")
public class RecommenderController {
    @Autowired
    private RecommenderService recommenderService;

    @AssertAuth
    @GetMapping("/list")
    public Result recommenderList() {
        String mobile = SecurityContextHolder.getContext().getMobile();
        return Result.ok(recommenderService.recommenderList(mobile));
    }

    @AssertAuth
    @GetMapping("/poster")
    public Result poster() {
        String mobile = SecurityContextHolder.getContext().getMobile();
        return Result.ok(recommenderService.poster(mobile, DateTime.now()));
    }


    @GetMapping("/qrcode")
    public void qrcode(@RequestParam String mobile, HttpServletResponse response) throws IOException {
        Verify.isTrue(MobileUtils.isValidMobile(mobile), "请输入合法的手机号码");
        String recommend_id = recommenderService.getRecommendId(mobile);
        QRCode.from("http://www.meisiabc.com/h5/form.html?recommend_id=" + recommend_id).to(ImageType.PNG).withSize(250, 250).withHint(EncodeHintType.MARGIN, 1).writeTo(response.getOutputStream());
        response.setContentType("image/png");
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @GetMapping("/wechat/qrcode")
    public void wechatQrcode(@RequestParam String mobile, HttpServletResponse response) throws IOException {
        Verify.isTrue(MobileUtils.isValidMobile(mobile), "请输入合法的手机号码");
        InputStream inputStream = recommenderService.wechatQrcode(mobile);
        ByteStreams.copy(inputStream, response.getOutputStream());
        response.setContentType("image/png");
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
